<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="dataForm.userName"
              placeholder="登录帐号"
            ></el-input> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="dataForm.mobile"
              placeholder="手机号"
            ></el-input> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickName">
            <el-input
              v-model="dataForm.nickName"
              placeholder="昵称"
            ></el-input> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="dataForm.email"
              placeholder="邮箱"
            ></el-input> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="部门" prop="deptId">
            <el-popover
              ref="menuListPopover"
              placement="bottom-start"
              trigger="click"
            >
              <el-tree
                :data="deptList"
                :props="deptListTreeProps"
                node-key="deptId"
                ref="menuListTree"
                @current-change="deptListTreeCurrentChangeHandle"
                :highlight-current="true"
                :expand-on-click-node="false"
              >
              </el-tree>
            </el-popover>
            <el-input
              v-model="dataForm.deptName"
              v-popover:menuListPopover
              :readonly="true"
              placeholder="点击选择部门"
              class="menu-list__input"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位" prop="jobIdList">
            <el-select
              v-model="dataForm.jobIdList"
              placeholder="请选择岗位"
              multiple
              style="width:100%"
            >
              <el-option
                v-for="item in jobList"
                :key="item.jobId"
                :label="item.name"
                :value="item.jobId"
              >
              </el-option>
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="dataForm.gender" style="width: 178px">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group
              v-model="dataForm.status"
              :disabled="userId === dataForm.userId"
            >
              <el-radio :label="0">禁用</el-radio>
              <el-radio :label="1">正常</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="角色" prop="roleIdList">
        <el-select
          v-model="dataForm.roleIdList"
          placeholder="请选择角色"
          multiple
          style="width:100%"
        >
          <el-option
            v-for="role in roleList"
            :key="role.roleId"
            :label="role.roleName"
            :value="role.roleId"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from "@/utils/validate";
export default {
  data() {
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error("密码不能为空"));
      } else {
        callback();
      }
    };
    var validateComfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error("确认密码不能为空"));
      } else if (this.dataForm.password !== value) {
        callback(new Error("确认密码与密码输入不一致"));
      } else {
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error("邮箱格式错误"));
      } else {
        callback();
      }
    };
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    return {
      deptListTreeProps: {
        children: "children",
        label: "name"
      },
      visible: false,
      roleList: [],
      dataForm: {
        jobId: "",
        id: 0,
        userName: "",
        password: "",
        comfirmPassword: "",
        salt: "",
        email: "",
        mobile: "",
        roleIdList: [],
        status: 1,
        gender: "男",
        deptId: "",
        deptName: "",
        jobIdList: [],
        nickName: "",
        userId:0
      },
      deptList: [], //部门列表
      jobList: [], //岗位列表
      dataRule: {
        userName: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [{ validator: validatePassword, trigger: "blur" }],
        comfirmPassword: [
          { validator: validateComfirmPassword, trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
          {
            min: 0,
            message: "最多输入255个字符",
            max: 255
          }
        ]
      }
    };
  },
  created() {
    console.log("this.userId", this.userId);
    this.initJobList();
    this.initDeptList();
  },
  props: {
    userId: {
      type: Number
    },
    deptName: {
      type: String
    },
    addDeptId:{
      type: Number
    },
    addDeptName:{
     type: String
    }
  },
  methods: {
    //部门树选中
    deptListTreeCurrentChangeHandle(data, node) {
      debugger;
      this.dataForm.deptId = data.deptId;
      this.dataForm.deptName = data.name;
    },
    initDeptList() {
      this.$http({
        url: this.$http.adornUrl("/sys/dept/selectDeptList"),
        method: "get",
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.deptList = data.deptList;
        console.log("this.deptList", this.deptList);
      });
    },
    //初始化岗位列表
    initJobList() {
      this.$http({
        url: this.$http.adornUrl("/sys/job/jobList"),
        method: "get",
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.jobList = data && data.code === 0 ? data.jobDtoList : [];
        console.log("this.jobList", this.jobList);
      });
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.$http({
        url: this.$http.adornUrl("/sys/role/select"),
        method: "get",
        params: this.$http.adornParams()
      })
        .then(({ data }) => {
          this.roleList = data && data.code === 0 ? data.list : [];
        })
        .then(() => {
          this.visible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
          });
        })
        .then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
              method: "get",
              params: this.$http.adornParams()
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.dataForm.userId = data.user.userId,
                this.dataForm.userName = data.user.username;
                this.dataForm.salt = data.user.salt;
                this.dataForm.email = data.user.email;
                this.dataForm.mobile = data.user.mobile;
                this.dataForm.nickName = data.user.nickName;
                this.dataForm.roleIdList = data.user.roleIdList;
                this.dataForm.jobIdList = data.user.jobIdList;
                this.dataForm.status = data.user.status;
                this.dataForm.gender = data.user.gender;
                if (data.user.deptId !== "" && data.user.deptId !== null) {
                  this.dataForm.deptId = data.user.deptId;
                  this.dataForm.deptName = this.deptName;
                }else{
                  this.dataForm.deptName = "";
                }
              }
            });
          }else{
            debugger
            console.log(this.addDeptId,this.addDeptName);
            if(this.addDeptId !== undefined){
              this.dataForm.deptId = this.addDeptId;
            }
            if(this.addDeptName !== undefined){
               this.dataForm.deptName = this.addDeptName;
            }
          }
        });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/sys/user/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              userId: this.dataForm.id || undefined,
              username: this.dataForm.userName,
              deptId: this.dataForm.deptId,
              nickName: this.dataForm.nickName,
              gender: this.dataForm.gender,
              email: this.dataForm.email,
              mobile: this.dataForm.mobile,
              status: this.dataForm.status,
              roleIdList: this.dataForm.roleIdList,
              jobIdList: this.dataForm.jobIdList
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
